package com.fzdy.product.config;

import com.fzdy.product.entity.User;
import com.fzdy.product.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userInfo = (User) principalCollection.getPrimaryPrincipal();
        authorizationInfo.addRole(userInfo.getRole().getName());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.login(token.getUsername(), new String(token.getPassword()));
        if (user == null) {
            throw new AccountException("用户名或者账号错误");
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
